//
//  UPOrderSearchViewController.m
//  LoveFreshBee
//
//  Created by wyzc on 16/6/20.
//  Copyright © 2016年 叶落知秋. All rights reserved.
//
#define POSTURL @"http://m.beequick.cn/data/searchHot?lat=39.977846184473&lng=116.49718705041&simulate_mobile=true&asid=575d39f34d1f38454&_r=0.46102569531194526&reflogid=57678de5e04ae8090&shopId=3248&bigids=2,0"
#import "UPOrderSearchViewController.h"
#import <FMDatabase.h>


@interface UPOrderSearchViewController ()<UISearchBarDelegate>
@property(nonatomic,weak)UIView *hotSearchView;
@property(nonatomic,weak)UISearchBar *searchBar;
@property(nonatomic,strong)FMDatabase *db;
//存放历史记录
@property(nonatomic,weak)UIView *historyView;
//存放历史记录的label
@property(nonatomic,weak)UILabel *historyLabel;
//存放历史记录的button
@property(nonatomic,weak)UIButton *historyButton;

@end

@implementation UPOrderSearchViewController
-(FMDatabase *)db
{
    if(_db==nil){
        NSString *cachePath=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"search.sqlite"];
        NSLog(@"%@",cachePath);
        
        _db=[FMDatabase databaseWithPath:cachePath];
        BOOL res=[_db open];
        if (res) {
            NSString *table=@"create table if not exists search(sid integer primary key autoincrement,content text not null)";
            [_db executeUpdate:table];
        }
    }
    return _db;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self sendPostRequest];
    [self setNavBar];
    [self createScrollView];
    
    
}
//从数据库中搜索过得历史记录
-(void)loadHistoryFromDb
{
    NSString *select=@"select content from search order by sid desc";
    FMResultSet *set=[self.db executeQuery:select];
    NSMutableArray *arr=[NSMutableArray array];
    while (set.next) {
        NSString *content=[set stringForColumnIndex:0];
        [arr addObject:content];
    }
    if (arr.count) {
        [self createButtonsWithArray:arr containerView:self.historyView];
        UIButton *lastBtn=[self.historyView.subviews lastObject];
        self.historyView.height=CGRectGetMaxY(lastBtn.frame)+15;
        self.historyButton.y=CGRectGetMaxY(self.historyView.frame)+20;
    }else{
        self.historyButton.hidden=YES;
        self.historyLabel.hidden=YES;
    }
    
}
//发送post请求，返回热门搜索数组
-(void)sendPostRequest
{
    NSURL *url=[NSURL URLWithString:POSTURL];
    //必须记住如果发送post请求必须创建一个可变请求
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //设置请求方式为post
    request.HTTPMethod=@"POST";
    NSString *bodyStr=@"zchtid=7917&zchtauth=";
    NSData *data=[bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody=data;
    NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data.length==0) {
            return ;
        }
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dataDict=dict[@"data"];
        if (dataDict==nil) {
            NSString *path=[[NSBundle mainBundle]pathForResource:@"shar.plist" ofType:nil];
            dict=[NSDictionary dictionaryWithContentsOfFile:path];
            
            dataDict=dict[@"data"];
        }
       // [dict writeToFile:@"/Users/wyzc/Desktop/cat.plist" atomically:YES];
        
        NSArray *arr=dataDict[@"hotquery"];
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self createButtonsWithArray:arr containerView:self.hotSearchView];
            //获取最后一个按钮
            UIButton *lastBtn=[self.hotSearchView.subviews lastObject];
            //设置热门搜索view的高度
            self.hotSearchView.height=CGRectGetMaxY(lastBtn.frame)+30;
            //设置历史记录的标签的y坐标
            self.historyLabel.y=CGRectGetMaxY(self.hotSearchView.frame)+50;
            //设置历史记录view的y坐标
            self.historyView.y=CGRectGetMaxY(self.historyLabel.frame)+20;
            //调用。。。
            [self loadHistoryFromDb];
        }];
    }];
    [dataTask resume];

}

-(void)createButtonsWithArray:(NSArray *)arr containerView:(UIView *)containerView
{
    //遍历数组中的每一个字符串，把字符串转换成按钮，然后添加到热门搜索view中去
    int margin=10;
    int btnx=0;
    int btny=0;
    int btnW=80;
    int btnH=30;
    int row=0;
    UIButton *beforeBtn=nil;//保存当前按钮的前一个按钮
    for(int i=0;i<arr.count;i++)
    {
//        int col=i%4;
//        int row=i/4;
//        btnx=margin+(btnW+margin)*col;
//        btny=margin+(btnH+margin)*row;
        
        UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(btnx, btny, btnW, btnH)];
        [containerView  addSubview:btn];
        btn.titleLabel.font=[UIFont systemFontOfSize:13];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        //刚好把内容包裹起来
        [btn sizeToFit];
        btn.width+=20;
        CALayer *layer=btn.layer;
        layer.cornerRadius=13;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
       btn.backgroundColor=[UIColor whiteColor];
        //设置X坐标
        if (beforeBtn==nil) {
            btn.x=margin;
        }else{
            btn.x=CGRectGetMaxX(beforeBtn.frame)+margin;
        }
        beforeBtn=btn;
        //设置y坐标
        if (btn.x+btn.width>self.hotSearchView.width) {
            
            btn.x=margin;
            row++;
        }
       btn.y=2*margin+(btnH+margin)*row;
        [btn addTarget:self action:@selector(setSearchContent:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
}
-(void)setSearchContent:(UIButton *)btn
{
    
    //currentTitle：获取按钮现实的文字
    self.searchBar.text=[btn currentTitle];
    [self saveToDb:self.searchBar.text];
    for (UIButton *btn in self.historyView.subviews) {
        [btn removeFromSuperview];
    }
    [self loadHistoryFromDb];
    self.historyLabel.hidden=NO;
    self.historyButton.hidden=NO;
}
//存放查询内容到数据库，不存在，就添加到数据库，否则不添加
-(void)saveToDb:(NSString *)content
{
   //1.判断添加的neir是否存在
    NSString *select=[NSString stringWithFormat:@"select content from search where content ='%@'",content];
    //结果集，存放查询出来的数据
    FMResultSet *set=[self.db executeQuery:select];
    //判断查询的内容在数据库中是否存在
    if (set.next) {
        
    
        
        return;
    }
    NSString *insert=[NSString stringWithFormat:@"insert into search (content) values('%@')",content];
    [self.db executeUpdate:insert];
}
/**
 *  创建滚动视图
 */
-(void)createScrollView
{
    UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:scrollView];
    scrollView.backgroundColor=UPColor(239, 239, 239);
    //创建热门搜索标签
    int hotLabelX=10;
    int hotLabelY=10;
    int hotLabelW=UPSreenW-hotLabelX;
    int hotLabelH=30;
    UILabel *hotSearchLabel=[[UILabel alloc] initWithFrame:CGRectMake(hotLabelX, hotLabelY, hotLabelW, hotLabelH)];
    hotSearchLabel.text=@"热门搜索";
    hotSearchLabel.textColor=UPColor(162, 162, 162);
    [scrollView addSubview:hotSearchLabel];
    
    //创建热门搜索View
    int hotSearchViewX=hotLabelX;
    int hotSearchViewY=CGRectGetMaxY(hotSearchLabel.frame)+2;
    int hotSearchViewW=hotLabelW;
    UIView *hotSearchView=[[UIView alloc] initWithFrame:CGRectMake(hotSearchViewX, hotSearchViewY, hotSearchViewW, 100)];
    hotSearchView.backgroundColor=[UIColor clearColor];
    [scrollView addSubview:hotSearchView];
    
    //创建--历史记录标签
    int historyLabelX=hotLabelX;
    int histortLabelY=CGRectGetMaxY(hotSearchView.frame)+30;
    int historyLabelW=hotLabelW;
    int historyLabelH=hotLabelH;
    UILabel *historyLabel=[[UILabel alloc] initWithFrame:CGRectMake(historyLabelX, histortLabelY, historyLabelW, historyLabelH)];
    self.historyLabel=historyLabel;
    historyLabel.textColor=hotSearchLabel.textColor;
    historyLabel.text=@"历史记录";
    [scrollView addSubview:historyLabel];
    
    //创建历史记录view
    int historyViewX=hotLabelX;
    int historyViewY=CGRectGetMaxY(historyLabel.frame)+2;
    int historyViewW=hotLabelW;
    UIView *historyView=[[UIView alloc] initWithFrame:CGRectMake(historyViewX, historyViewY, historyViewW, 100)];
    self.historyView=historyView;
    
    self.hotSearchView=hotSearchView;
    historyView.backgroundColor=[UIColor clearColor];
    [scrollView addSubview:historyView];
    
    
    
    //创建清空历史按钮
    CGFloat clearBtnX=UPSreenW*0.1;
    CGFloat clearBtnW=UPSreenW*0.8;
    CGFloat clearBtnH=30;
    CGFloat clearBtnY=CGRectGetMaxY(historyView.frame)+20;
    UIButton *clearBtn=[[UIButton alloc] initWithFrame:CGRectMake(clearBtnX, clearBtnY, clearBtnW, clearBtnH)];
    
    self.historyButton=clearBtn;
    [clearBtn setTitle:@"清空历史记录" forState:UIControlStateNormal];
    [clearBtn setTitleColor:UPColor(188, 188, 188) forState:UIControlStateNormal];
    CALayer *btnLayer=clearBtn.layer;
    btnLayer.borderColor=UPColor(188, 188, 188).CGColor;
    btnLayer.borderWidth=1;
    clearBtn.titleLabel.font=[UIFont systemFontOfSize:13];
    
    [clearBtn addTarget:self action:@selector(btnClearHistoryClick) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:clearBtn];
    
    
    scrollView.contentSize=CGSizeMake(UPSreenW, UPSreenH+1);
    
    
}
/**
 *  1.清除表中所有数据
    2.清除历史记录View中的所有子视图
    3.隐藏（或禁用）清除历史记录按钮
 */
-(void)btnClearHistoryClick
{
    NSString *delete=@"delete from search";
    BOOL res=[self.db executeUpdate:delete];
    if (res) {
        for (UIButton *btn in self.historyView.subviews) {
            [btn removeFromSuperview];
        }
    }
    self.historyButton.hidden=YES;//隐藏
   // self.historyView.hidden=YES;
    self.historyLabel.hidden=YES;
    //self.historyButton.enabled=NO;--禁用
}
-(void)setNavBar
{
    //设置返回按钮
    UIButton *backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    //返回按钮点击事件
    [backBtn addTarget:self action:@selector(btnBackClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"v2_goback"] forState:UIControlStateNormal];
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc] initWithCustomView:backBtn];
    //创建一个固定宽度的item
    UIBarButtonItem *leftFixedItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //设置向左移动的距离
    leftFixedItem.width=-10;
    
    self.navigationItem.leftBarButtonItems=@[leftFixedItem,leftItem];
    
    //设置中间搜索框
    UISearchBar *searchBar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 0, 30)];
    searchBar.placeholder=@"请输入商品名称";
    self.searchBar=searchBar;
    //设置代理，这样的话就可以监听弹出键盘搜索按钮点击是出发的事件
    searchBar.delegate=self;
    self.navigationItem.titleView=searchBar;
    
}
//实现点击按钮点击事件
-(void)btnBackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**

 *  搜索框调用时就会触发(调用)该方法
 */
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //获取搜索框中的内容
    NSString *searchText=searchBar.text;
    [self saveToDb:searchText];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
